<template>
  <section class="todoapp">
    <todo-header @add="add"></todo-header>
    <todo-main
      @changeAll="handleAll"
      :allselected="allselected"
      :list="newlist"
      @del="del"
      @changeState="changeState"
    ></todo-main>
    <todo-footer
      :allcom="allcom"
      @desAllCom="desAllCom"
      :flag="flag"
      @changeFlag="changeFlag"
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "@/components/TodoHeader.vue";
import TodoMain from "@/components/TodoMain.vue";
import TodoFooter from "@/components/TodoFooter.vue";
export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      flag: "all",
      list: JSON.parse(localStorage.getItem("list")) || [],
    };
  },
  methods: {
    del(id) {
      this.list = this.list.filter((item) => item.id != id);
    },
    add(todo) {
      this.list.unshift({
        id: Date.now(),
        name: todo,
        isDone: false,
      });
    },
    changeState(id) {
      let res = this.list.find((item) => item.id === id);
      res.isDone = !res.isDone;
    },
    desAllCom() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    changeFlag(val) {
      this.flag = val;
    },

    handleAll(val) {
      // console.log(val);
      this.list.forEach(item=> item.isDone = val);
    },
  },
  computed: {
    allcom() {
      return this.list.filter((item) => !item.isDone).length;
    },
    newlist() {
      if (this.flag === "all") {
        return this.list;
      } else if (this.flag === "ing") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list.filter((item) => item.isDone);
      }
    },
  },
  watch: {
    list: {
      handler(newval) {
        localStorage.setItem("list", JSON.stringify(newval));
      },
      deep: true,
    },
  },
};
</script>

<style>
</style>
